﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Media;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Table_pet.background;
using Table_pet.background.Classes;

namespace clock.time
{
    /// <summary>
    /// 时钟类
    /// </summary>
    public class TimeServer : AuxiliaryExtensionMethod
    {
        
        FileStreamReader fsr = new FileStreamReader();
        SoundPlayer sp = new System.Media.SoundPlayer();
        public TimeServer()
        {

        }

        #region 闹钟提醒

        #region 读取数据库存储提醒时间信息
        private List<object[]> lob = new List<object[]>();
        public List<object[]> Lob
        {
            get { return lob; }
            set { lob = value; }
        }
        #endregion

        //删除闹钟
        public void TimeDelete(long guid)
        {
            DB_api.deleteClockById(guid);
        }
        /// <summary>
        /// 加载时间表中需要提醒的数据
        /// </summary>
        /// <returns></returns>
        public bool LoadTimePlan()
        {
            var data = DB_api.readAllClock();
            //查询数据库，加载提醒列表
            if (data!=null)
            {
                List<DateTime> ldt = new List<DateTime>();
                Holiday hi = new Holiday();
                bool flag = hi.GetIsHolidaybitefu(DateTime.Now.ToString("yyyyMMdd"));
                //通过 DateTime.Now.DayOfWeek 判断今天是星期几
                string Weeks = WordConversions.ToCharacter(Convert.ToInt32(DateTime.Now.DayOfWeek).ToString());
                string Sunday = ConfigurationManager.AppSettings["Sunday"];
                //因为星期天 DateTime.Now.DayOfWeek 返回 0 所以要特殊处理一下。这里默认 Sunday 是星期天。
                string Week = Convert.ToInt32(DateTime.Now.DayOfWeek) < 1 ? Sunday.Substring(Sunday.Length - 1) : Weeks;
                //判断当天星期几。筛选按照星期循环的数据当天是否需要提醒。
                foreach (var item in data)
                {
                    int IntervalTime = item.IntervalTime;
                    bool isflag = false;
                    if (IsNotNull(item.RemindType) && item.RemindType.ToString() != "0" && item.RemindType.IndexOf(Week) >= 0)
                    {
                        object[] obj = new object[] { item.Id.ToString(), item.SettingTime, item.Ring };
                        this.Lob.Add(obj);
                        isflag = true;
                    }
                    if (flag)
                    {
                        if (IsNotNull(item.RemindType) && item.RemindType.ToString() == "0")
                        {
                            object[] obj = new object[] { item.Id.ToString(), item.SettingTime, item.Ring.ToString() };
                            this.Lob.Add(obj);
                            isflag = true;
                        }
                    }
                    if (item.RemindNumber > 0 && (item.SettingTime.ToString("yyyyMMdd") == DateTime.Now.ToString("yyyyMMdd")))
                    {
                        //如果是按次数提醒则在Id字段处做标记。方便提醒完全部次数修改数据库
                        object[] obj = new object[] { item.Id.ToString() + "_Number", item.SettingTime, item.Ring };
                        this.Lob.Add(obj);
                        isflag = true;
                    }
                    if (isflag == true)
                    {
                        if (IntervalTime > 0 )
                        {
                            for (int i = 0; i < 3; i++)
                            {
                                object[] obj = new object[] { item.Id.ToString(), (item.SettingTime.AddMinutes(IntervalTime), item.Ring) };
                                this.Lob.Add(obj);
                            }
                        }
                    }
                }
            }
            //生成列表后开启线程，循环执行提醒方法。
            Thread thread = new Thread(Remind);
            thread.IsBackground = true;
            thread.Start();
            return true;
        }

        /// <summary>
        /// 提醒方法
        /// </summary>
        void Remind()
        {
            List<string> ldt = new List<string>();
            foreach (object[] item in this.Lob)
            {
                ldt.Add(((DateTime)item[1]).ToShortTimeString());
            }
            //判断数据库中三种循环方式当天有没有闹钟
            while (this.Lob.Count > 0)
            {
                DateTime Current = DateTime.Now;
                //如果当前时间的时，分数值与列表值相等则记录，并提醒。
                if (ldt.Contains(Current.ToShortTimeString()))
                {
                    List<string> SqlKey = new List<string>();
                    List<object[]> RemoveKey = new List<object[]>();
                    string Ring = "";
                    foreach (object[] items in this.Lob)
                    {
                        if (((DateTime)items[1]).ToShortTimeString() == Current.ToShortTimeString())
                        {
                           
                            if (Ring == "" && IsNotNull(items[2].ToString()))
                                Ring = items[2].ToString();
                             //如果数据库中有设定铃声则播放铃声否则播放默认铃声
                             if (Ring != "")
                            {
                                sp.SoundLocation = fsr.SplicePath("voice") + @"\" + Ring;
                                sp.Play();
                            }
                            else
                            {
                                SystemSounds.Beep.Play();
                            }
                            if (items[0].ToString().IndexOf("_Number") >= 0)
                            {
                                SqlKey.Add(items[0].ToString());
                            }
                            RemoveKey.Add(items);
                        }
                    }
                   
                    
                    //提醒过后的从列表中移除，知道列表中没有要提醒的则退出循环。
                    foreach (var item in RemoveKey)
                    {
                        this.Lob.Remove(item);
                    }
                    //如果是按次数提醒的在提醒后修改数据库次数
                    foreach (var item in SqlKey)
                    {
                        long Id = long.Parse(item.Substring(0, item.IndexOf("_")));
                        DB_api.searchClockById(item[0]).RemindNumber--;
                    }
                    //做完处理后停止运行一段时间。不重复判断浪费系统资源
                    Thread.Sleep(50000);
                }
            }
        }
        #endregion

       

        
        /// <summary>
        /// 设定时间入库
        /// </summary>
        /// <param name="Hour">小时</param>
        /// <param name="Minute">分钟</param>
        /// <param name="RemindType">提醒类型：周一 - 周日，0：工作日</param>
        /// <param name="Remarks">备注</param>
        /// <param name="Time">上午下午</param>
        /// <param name="RemindNumber">提醒次数，-1：循环提醒</param>
        /// <returns></returns>
        public string AddTimingPlan(string Hour, string Minute, string RemindType = "", string Time = "上午", string Ring = "", int RemindNumber = -1, int IntervalTime = 0)
        {

            if ((IsNotNull(RemindType) || RemindNumber > 0) && !(IsNotNull(RemindType) && RemindNumber > 0))
            {
                if (Time == "下午")
                    Hour = (int.Parse(Hour) + 12).ToString();
                DateTime dt = DateTime.Parse(Hour + ":" + Minute);
                ClockModel Tp = new ClockModel(dt,RemindNumber,Ring,RemindType,IntervalTime);
                //Frequency = 3;
                try
                {
                    if (DB_api.AddClock(Tp)!=0)
                        return "闹钟-设置成功！";
                    else
                        return "闹钟-设置失败！";
                }
                catch (Exception ex)
                {
                    return "闹钟-入库失败！";
                }
            }
            else
                return "闹钟-设置信息有误！";
        }

      

    // 拼接闹钟列表

    public DataTable SelectTimingPlaninfo()
        {
            var data = DB_api.readAllClock();
            DataTable TimingPlaninfo = new DataTable();
            TimingPlaninfo.Columns.Add("提醒时间");
            TimingPlaninfo.Columns.Add("提醒方式");
            TimingPlaninfo.Columns.Add("再响间隔");
            TimingPlaninfo.Columns.Add("铃声");

            foreach (var item in data)
            {
                DataRow dr = TimingPlaninfo.NewRow();
                dr["提醒时间"] = DateTime.Parse(item.SettingTime.ToString()).ToShortTimeString();
                if (Convert.ToInt32(item.RemindNumber.ToString()) > 0)
                    dr["提醒方式"] = item.RemindNumber.ToString() + "次";
                else if (item.RemindType.ToString() == "0")
                    dr["提醒方式"] = "法定节假日";
                else if (item.RemindType.ToString() != "0" && IsNotNull(item.RemindType.ToString()))
                    dr["提醒方式"] = item.RemindType.ToString();
                if (item.IntervalTime > 0 )
                    dr["再响间隔"] = item.IntervalTime.ToString() + "分钟，" + "3" + "次";
                if (IsNotNull(item.Ring.ToString()))
                    dr["铃声"] = item.Ring.ToString();

                TimingPlaninfo.Rows.Add(dr);
            }
            return TimingPlaninfo;
        }


    }
}
